/*
 * @Description: 
 * @Autor: ilmari
 * @Date: 2021-05-18 09:32:28
 * @LastEditors: ilmari
 * @LastEditTime: 2021-05-18 10:23:39
 */
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rcmd/app/modules/rcmd/models/rlog.dart';
import '../controllers/rcmd_controller.dart';
import 'persist_page.dart';

class BaseController extends GetxController {}

class RcmdPage extends GetView<RcmdController> with UtilView {
  @override
  Widget build(BuildContext context) {
    return Column(children: [
      _getToolBar(context),
      Expanded(
        child: _getBody(context),
      )
    ]);
  }

  Widget _getPageIndicate(List<List> pages) {
    return GetBuilder(
      builder: (context) {
        var widgets = pages.skip(1).map((e) {
          var title = e[0];
          return OutlinedButton(
              onPressed: () {
                controller.selectPage(title);
              },
              child: Text(
                title,
                style: TextStyle(
                    color: controller.active.value == title
                        ? Colors.red
                        : Colors.black),
              ));
        }).toList(growable: false);
        return Row(
          children: widgets,
        );
      },
      init: controller.pageSel,
    );
  }

  Widget _getToolBar(BuildContext context) {
    String filter = "";
    final isReg = false.obs;
    final isExclude = false.obs;
    return Row(
      children: [
        IconButton(
            icon: Icon(
              Icons.remove_circle,
              color: Colors.redAccent,
            ),
            padding: EdgeInsets.all(4),
            iconSize: 32,
            tooltip: "移除当前页面",
            onPressed: controller.removeCurrentPage),
        IconButton(
          icon: Icon(Icons.add_box),
          padding: EdgeInsets.all(4),
          iconSize: 32,
          tooltip: "新建页面",
          onPressed: () {
            _addPage(context);
          },
        ),
        IconButton(
          icon: Icon(Icons.copy_outlined),
          padding: EdgeInsets.all(4),
          iconSize: 32,
          tooltip: "复制当前页",
          onPressed: () {
            _dupPage(context);
          },
        ),
        IconButton(
          icon: Icon(Icons.save_outlined),
          padding: EdgeInsets.all(4),
          iconSize: 32,
          tooltip: "保存",
          onPressed: () {
            _savePage(context);
          },
        ),
        IconButton(
          icon: Icon(Icons.system_update_alt),
          padding: EdgeInsets.all(4),
          iconSize: 32,
          tooltip: "加载",
          onPressed: () {
            _loadPage(context);
          },
        ),
        IconButton(
          icon: Icon(Icons.home_outlined),
          padding: EdgeInsets.all(4),
          iconSize: 32,
          tooltip: "主页",
          onPressed: () {
            controller.pageController?.animateToPage(0,
                duration: Duration(milliseconds: 300), curve: Curves.easeInOut);
          },
        ),
        //Expanded(child: Obx(()=>Row(children: _getPageIndicate()))),
        Expanded(
          child: _getPageIndicate(controller.pages),
          flex: 2,
        ),
        Obx(() => _checkbox("正则表达式", isReg.value, (x) {
              isReg.value = x ?? false;
            })),
        Obx(() => _checkbox("排除", isExclude.value, (x) {
              isExclude.value = x ?? false;
            })),
        Expanded(
          child: textField(controller.filter.value, (text, over) {
            filter = text.trim();
            controller.filter.value = filter;
            if (over && filter.isNotEmpty)
              _doFind(FilterRuler(filter,
                  isExclude: isExclude.value, reg: isReg.value));
          }),
          flex: 1,
        ),
        padding(
            TextButton(
                onPressed: () {
                  if (filter.isNotEmpty)
                    _doFind(FilterRuler(filter,
                        isExclude: isExclude.value, reg: isReg.value));
                },
                child: Text("添加规则")),
            vertical: 0,
            horizontal: 10),
      ],
    );
  }

  Widget _getBody(BuildContext context) {
    return Obx(() => PageView.builder(
          itemBuilder: (context, index) {
            return controller.pages[index][1];
          },
          itemCount: controller.pageCount.value,
          controller: controller.pageController,
        ));
  }

  void _addPage(BuildContext context) {
    controller.addCustomCmdPage();
  }

  void _addCustomCmdPage(BuildContext context) {
    controller.addCustomCmdPage();
    pop(context);
  }

  void _addInnerLogPage(BuildContext context) {
    controller.addInnerLogPage();
    pop(context);
  }

  Widget _checkbox(String title, bool check, Function(bool?) onChanged) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [Text(title), Checkbox(value: check, onChanged: onChanged)],
    );
  }

  static void pop(BuildContext context) {
    Navigator.of(context).pop();
  }

  void _doFind(FilterRuler filter) {
    final page = controller.activePage;
    if (page == null) return;
    page.addFilter(filter);
  }

  void _dupPage(BuildContext context) {
    final page = controller.activePage;
    if (page == null) return;
    controller.addCustomCmdPage(controller:page);
  }

  void _savePage(BuildContext context) {
    final page = controller.activePage;
    if (page == null) return;
    getInputText(context, "请输入保存的文件名:(扩展名.log)").then((value){
      if (value.isEmpty)  return ;
      if (!value.endsWith(".log")) {
        value = "$value.log";
      }
      page.saveLines(value);
    });
  }

  void _loadPage(BuildContext context) {
    final page = controller.activePage;
    if (page == null) return;
    Directory current = Directory.current;
    current.list(followLinks: false)
      .where((entry) => FileSystemEntity.isFileSync(entry.path))
      .map((entry) => entry.path)
      .where((path) => path.endsWith(".log")).toList()
      .then((files) {
        selFromList(context, files).then((i){
          if (i>=0 && i<files.length) {
            page.loadLines(files[i]);
          }
        });
      });
  }
}
